import random
##use PluginLoader class to use plugins.
class PluginManager():
	def __init__(self, directory):
		## @var _plugins
		# dictionary to save modules
		self._plugins = {}
		self._directory = directory
	
	##load the plugin @see _directory.
	def load_plugin(self, name):
		try:
			mod = __import__(self._directory+".mod_%s"%name, fromlist=[self._directory])
			self._plugins[name] = mod
			if "start" in dir(mod):
				mod.start()
		except (ImportError):
			raise ImportError('plugin %s cannot loaded')
		except:
			raise Exception('cannot load and run this plugin: %s'%name)

	##unload the plugin if it is exists.
	#quit thread if it has, and exit
	def unloadPlugin(self, name):
		if name in self._plugins:
			if "quit" in dir(self._plugins[name]):
				self._plugins[name].quit()
				self._plugins[name].join()
			self._plugins.pop(name)
	
	##unload all plugin.
	#useful when program is going to shutdown
	def unloadAll(self):
		for pluginname in self.getPluginsName():
			self.unloadPlugin(pluginname)

	## get all of plugin's name
	#@return list of plugin's name
	def getPluginsName(self):
		return self._plugins.keys()

	##when you mentioned, use this function to get a auto-generated reply
	#@param args just args (by list)
	#@param kwds just args (by dict)
	#@return a unicode string to reply
	def getReply(self, *args, **kwds):
		reply_text = []
		reply_header = ''
		reply_footer = ''

		##@var passed
		#when all of plugin cannot reply, this is False
		passed = False
		for module in self._plugins.values():
			if "reply" in dir(module):
				res = module.reply(**kwds)
				if res['text']:
					reply_text.append(res['text'])
					if res['header']:
						reply_header += res['header']+' '
					if res['footer']:
						reply_footer += ' '+res['footer']
					passed = True
					break

		if passed == False:
			#all plugin cannot reply.
			#so lets random play!
			modulenames = self.getPluginsName()
			random.shuffle(modulenames)
			for modulename in modulenames:
				module = self._plugins[modulename]
				if "replyBackup" in dir(module):
					res = module.replyBackup(**kwds)
					if res['text']:
						reply_text.append(res['text'])
					if res['header']:
						reply_header += res['header']+' '
					if res['footer']:
						reply_footer += ' '+res['footer']
					break

		reply_str = u"@%s %s%s%s"%(kwds['username'], reply_header, ' '.join(reply_text), reply_footer)

		return reply_str
